import React from 'react';
import {
  Row,
  Col,
  Table,
  Switch,
  notification,
  Icon,
  Button,
  Input,
  Modal,
  Form,
  Tooltip,
  InputNumber
} from 'antd';
import axios from 'axios';
import intercept from '../../utils/intercept';
import {config} from 'utils';
import './less/common.less'
const Search = Input.Search;
const FormItem = Form.Item;

class InsuranceTypes extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      dataSource: [],
      loading: false,
      visible: false
    };
  };
  componentDidMount() {
    this.getInsureInfo();
  };
  search = (value) => {};
  getInsureInfo = () => {
    const token = sessionStorage.getItem("token");
    this.setState({loading: true});
    axios
      .get(`${config.api}CustomService/GetInsuranceTypes`, {
      headers: {
        Authorization: 'Bearer ' + token
      }
    })
      .then((res) => {
        //console.log(res);
        this.setState({loading: false, dataSource: res.data.insuranceTypes});
      })
      .catch(err => {
        intercept;
      })
  };
  switchChange = (checked, productCode) => {
    const token = sessionStorage.getItem("token");
    this.setState({loading: true});
    axios.post(`${config.api}CustomService/EnableInsuranceType`, {
      productCode: productCode,
      isEnable: checked
    }, {
      headers: {
        Authorization: 'Bearer ' + token
      }
    }).then((res) => {
      //console.log(res);
      if (res.data.result) {
        this.openNotification("修改保险类型", `${checked
          ? '开启'
          : '关闭'}保险类型成功`, "#108ee9");
      } else {
        this.openNotification("修改保险类型", res.data.errorMessage, "red");
      }
      this.setState({loading: false});
    })
    .catch(err => {
      intercept;
    })
  }
  openNotification = (title, desc, color) => {
    notification.open({message: title, description: desc, icon: <Icon type="smile-circle" style={{
      color: color
    }}/>});
  };
  showAddActivityModel = () => {
    this.setState({visible: true})
  }
  handleReset = () => {
    this
      .props
      .form
      .resetFields();
  }
  handleCancel = (e) => {
    //console.log(e);
    this.setState({visible: false});
  }
  handleSubmit = (e) => {
    e.preventDefault();
    this
      .props
      .form
      .validateFieldsAndScroll((err, values) => {
        //console.log(values);
        if (!err) {
          const postdata = {
            productCode: values.productCode,
            productId: values.productId,
            organization: values.organization,
            insureType: values.insureType,
            insureTypeId: values.insureTypeId,
            setName: values.setName,
            insureAmount: values.insureAmount,
            insurePrice: values.insurePrice,
            period: values.period,
            isEnable: values.isEnable
          }
          const token = sessionStorage.getItem("token");
          axios
            .post(`${config.api}CustomService/AddInsuranceType`, postdata, {
            headers: {
              Authorization: 'Bearer ' + token
            }
          })
            .then((res) => {
              //console.log("接口返回：",data);
              if (res.data.result) {
                this.openNotification("添加保险类型", "添加保险类型成功", "#108ee9");
                this
                  .props
                  .form
                  .resetFields();
                if (res.data.isAdd) {
                  var dataSource = this.state.dataSource;
                  dataSource.unshift(postdata);
                  this.setState({dataSource});
                }
              } else {
                this.openNotification("添加保险类型", res.data.errorMessage, "red");
              }
              this.setState({visible: false})
            })
            .catch(err => {
              intercept;
            })
        }
      });
  }
  editproduct = (ev, record) => {
    //console.log(record);
    this
      .props
      .form
      .setFieldsValue({
        productCode: record.productCode,
        productId: record.productId,
        organization: record.organization,
        insureType: record.insureType,
        insureTypeId: record.insureTypeId,
        setName: record.setName,
        insureAmount: record.insureAmount,
        insurePrice: record.insurePrice,
        period: record.period,
        isEnable: record.isEnable
      });
    this.setState({visible: true})
  }
  deleteproduct = (ev, record) => {
    const token = sessionStorage.getItem("token");
    axios.post(`${config.api}CustomService/DeleteInsuranceType`, {
      productCode: record.productCode
    }, {
      headers: {
        Authorization: 'Bearer ' + token
      }
    }).then((res) => {
      //console.log("接口返回：",data);
      if (res.data.result) {
        this.openNotification("删除保险类型", "删除保险类型成功", "#108ee9");
        var dataSource = this
          .state
          .dataSource
          .filter(item => item.productCode !== record.productCode);
        this.setState({dataSource});
      } else {
        this.openNotification("删除保险类型", res.data.errorMessage, "red");
      }
      this.setState({visible: false})
    })
    .catch(err => {
      intercept;
    })
  }
  render() {
    const columns = [
      {
        title: '产品编号',
        dataIndex: 'productCode',
        width: 150
      }, {
        title: '产品代码',
        dataIndex: 'productId',
        width: 150
      }, {
        title: '范围',
        dataIndex: 'organization',
        width: 150
      }, {
        title: '保险类型',
        dataIndex: 'insureType',
        width: 150
      }, {
        title: '名称',
        dataIndex: 'setName',
        width: 250
      }, {
        title: '保费',
        dataIndex: 'insurePrice',
        width: 150
      }, {
        title: '保额',
        dataIndex: 'insureAmount',
        width: 150
      }, {
        title: '有效期',
        dataIndex: 'period',
        width: 150
      }, {
        title: '状态',
        dataIndex: 'isEnable',
        width: 150,
        render: (text, record) => {
          return (
            <span>
              <Switch
                checkedChildren="开"
                unCheckedChildren="关"
                onChange={(checked, productCode) => {
                this.switchChange(checked, record.productCode)
              }}
                defaultChecked={record.isEnable}/>
            </span>
          )
        }
      }, {
        title: '操作',
        width: 250,
        key: 'action',
        render: (text, record) => {
          return (
            <span>
              <a className="operation"
                onClick={(ev, record) => {
                this.editproduct(ev, text)
              }}>编辑</a>
              <span className="ant-divider"/>
              <a className="operation"
                onClick={(ev, record) => {
                this.deleteproduct(ev, text)
              }}>删除</a>
            </span>
          )
        }
      }
    ];
    const className = "components-table-demo-nested";
    // const scroll = {
    //   y: 600
    // };
    const formItemLayout = {
      labelCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 6
        }
      },
      wrapperCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 14
        }
      }
    };

    const {getFieldDecorator} = this.props.form;
    return (
      <div className="orderinfo">
        <Row gutter={8} style={{
          marginTop: '20px'
        }}>
          <Col span={24}>
            <div className="insurance">
            查询保险：
              <Search
                placeholder="请输入任意查询条件"
                style={{
                width: 600,
                height:"34px"
              }}
                onSearch={value => this.search(value)}/>
              
            </div>
            <Button type="primary" className='newadd' onClick={this.showAddActivityModel}>添加保险类型</Button>
            <Table
              {...this.state}
              bordered={false}
              className={className}
              columns={columns}
             />
          </Col>
        </Row>
        <Modal
          title="添加活动记录"
          visible={this.state.visible}
          footer={null}
          width={700}
          onCancel={this.handleCancel}>
          <Form onSubmit={this.handleSubmit}>
            <Row>
              <Col span={12}>
                <FormItem
                  {...formItemLayout}
                  label={(
                  <span>
                    产品编号
                    <Tooltip title="自动填充">
                      <Icon type="question-circle-o"/>
                    </Tooltip>
                  </span>
                )}
                  hasFeedback>
                  {getFieldDecorator('productCode', {
                    rules: [
                      {
                        required: true,
                        message: 'Please input your traderaccount!',
                        whitespace: true
                      }
                    ]
                  })(<Input/>)}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label={(
                  <span>
                    产品ID
                    <Tooltip title="自动填充">
                      <Icon type="question-circle-o"/>
                    </Tooltip>
                  </span>
                )}
                  hasFeedback>
                  {getFieldDecorator('productId', {
                    rules: [
                      {
                        required: true,
                        message: 'Please input your traderaccount!',
                        whitespace: true
                      }
                    ]
                  })(<Input/>)}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label={(
                  <span>
                    范围
                    <Tooltip title="自动填充">
                      <Icon type="question-circle-o"/>
                    </Tooltip>
                  </span>
                )}
                  hasFeedback>
                  {getFieldDecorator('organization', {
                    rules: [
                      {
                        required: true,
                        message: 'Please input your traderaccount!',
                        whitespace: true
                      }
                    ]
                  })(<Input/>)}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label={(
                  <span>
                    保险类型
                    <Tooltip title="自动填充">
                      <Icon type="question-circle-o"/>
                    </Tooltip>
                  </span>
                )}
                  hasFeedback>
                  {getFieldDecorator('insureType', {
                    rules: [
                      {
                        required: true,
                        message: 'Please input your traderaccount!',
                        whitespace: true
                      }
                    ]
                  })(<Input/>)}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label={(
                  <span>
                    保险类型ID
                    <Tooltip title="自动填充">
                      <Icon type="question-circle-o"/>
                    </Tooltip>
                  </span>
                )}
                  hasFeedback>
                  {getFieldDecorator('insureTypeId', {
                    rules: [
                      {
                        required: true,
                        message: 'Please input your traderaccount!',
                        whitespace: true
                      }
                    ]
                  })(<Input/>)}
                </FormItem>
              </Col>
              <Col span={12}>
                <FormItem
                  {...formItemLayout}
                  label={(
                  <span>
                    名称
                    <Tooltip title="自动填充">
                      <Icon type="question-circle-o"/>
                    </Tooltip>
                  </span>
                )}
                  hasFeedback>
                  {getFieldDecorator('setName', {
                    rules: [
                      {
                        required: true,
                        message: 'Please input your traderaccount!',
                        whitespace: true
                      }
                    ]
                  })(<Input/>)}
                </FormItem>

                <FormItem
                  {...formItemLayout}
                  label={(
                  <span>
                    保费
                    <Tooltip title="用户缴纳的保险金额">
                      <Icon type="question-circle-o"/>
                    </Tooltip>
                  </span>
                )}
                  hasFeedback>
                  {getFieldDecorator('insurePrice', {
                    rules: [
                      {
                        required: true,
                        type: 'number',
                        step: 0.1,
                        precision: 2,
                        message: 'Please input your traderaccount!',
                        whitespace: true
                      }
                    ]
                  })(<InputNumber className='inputwidth'/>)}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label={(
                  <span>
                    保额
                    <Tooltip title="赔给用户的额度">
                      <Icon type="question-circle-o"/>
                    </Tooltip>
                  </span>
                )}
                  hasFeedback>
                  {getFieldDecorator('insureAmount', {
                    rules: [
                      {
                        required: true,
                        type: 'number',
                        step: 0.1,
                        precision: 2,
                        message: 'Please input your traderaccount!',
                        whitespace: true
                      }
                    ]
                  })(<InputNumber className='inputwidth'/>)}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label={(
                  <span>
                    有效期
                    <Tooltip title="自动填充">
                      <Icon type="question-circle-o"/>
                    </Tooltip>
                  </span>
                )}
                  hasFeedback>
                  {getFieldDecorator('period', {
                    rules: [
                      {
                        required: true,
                        type: 'number',
                        step: 0.1,
                        precision: 2,
                        message: 'Please input your traderaccount!',
                        whitespace: true
                      }
                    ]
                  })(<InputNumber className='inputwidth'/>)}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label={(
                  <span>
                    是否启用
                    <Tooltip title="自动填充">
                      <Icon type="question-circle-o"/>
                    </Tooltip>
                  </span>
                )}
                  hasFeedback>
                  {getFieldDecorator('isEnable', {
                    rules: [
                      {
                        required: true,
                        type: 'boolean',
                        message: 'Please input your traderaccount!',
                        whitespace: true
                      }
                    ]
                  })(<Switch defaultChecked={false}/>)}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={24}>
                <FormItem className="center">
                  <Button onClick={this.handleReset}>重置</Button>{' '}
                  <Button type="primary" htmlType="submit">确定</Button>
                </FormItem>
              </Col>
            </Row>
          </Form>
        </Modal>
      </div>
    )
  }
}
const InsuranceType = Form.create()(InsuranceTypes);
export default InsuranceType
